<?php
session_start();
include_once "regsettings.php";
include_once "regfunctions.php";

include_once REG_CONNECT_FILE;
include_once REG_QUERY_FILE;

if (isset($_REQUEST['username'])) {
	$username = $_REQUEST['username'];
	$username = regMakeSafe($username);
}
else {
	$username = "";
} 

if (isset($_REQUEST['password'])) {
	$password = $_REQUEST['password'];
	$password = regMakeSafe($password);
}
else {
	$password = "";
} 

if (isset($_REQUEST['check_password'])) {
	$check_password = $_REQUEST['check_password'];
	$check_password = regMakeSafe($check_password);
}
else {
	$check_password = "";
} 

if (isset($_REQUEST['firstname'])) {
	$firstname = $_REQUEST['firstname'];
	$firstname = regMakeSafe($firstname);
}
else {
	$firstname = "";
} 

if (isset($_REQUEST['lastname'])) {
	$lastname = $_REQUEST['lastname'];
	$lastname = regMakeSafe($lastname);
}
else {
	$lastname = "";
} 

if (isset($_REQUEST['email'])) {
	$email = $_REQUEST['email'];
	$email = regMakeSafe($email);
}
else {
	$email = "";
} 

if(!empty($_REQUEST['user_id'])){
	$user_id = $_REQUEST['user_id'];
}else if(!empty($_SESSION['user_id'])){
	$user_id = $_SESSION['user_id'];
}



if($_REQUEST['mode'] == 'Save'){
	$hashsalt = 'Change this default salt 0394ufw90w';
	$passhash = md5($hashsalt . $password);

	$qry_update_user = "UPDATE " . REG_USER_TABLE . " SET username = '$username', password = '$passhash', firstname='$firstname', 
	lastname='$lastname', email = '$email' WHERE user_id = " . $user_id ;

	do_query($qry_update_user);

	$message = "Registration details saved for $username ";
}
else if($_REQUEST['mode'] == 'Add'){
	$hashsalt = 'Change this default salt 0394ufw90w';
	$passhash = md5($hashsalt . $password);
	// get new user_id
	$user_id = lookup_value('max(user_id)', REG_USER_TABLE, " 1 ") + 1;

	//print "user_id is $user_id ";

	$qry_insert_user = "INSERT INTO " . REG_USER_TABLE . " (user_id, username, password, firstname, lastname, email) VALUES 
	($user_id, '$username', '$passhash', '$firstname', '$lastname', '$email') ;";
	do_query($qry_insert_user);

	$qry_assign_role = "INSERT INTO ". REG_USERS_ROLES ." (user_id, role_id) VALUES ($user_id, " . REG_ROLE_DEFAULT . ")";
	do_query($qry_assign_role);
	
	$message = "New User $username created";
	// alternate to get last added id
	// user_id = mysql_insert_id();
}

// set Session and login for new user_id (NOT USED)
function DoRegUserLogin($user_id){
	$username = lookup_value('username',REG_USER_TABLE," user_id = $user_id ");
	$_SESSION['user_id'] = $user_id;
	$_SESSION['username'] = $username;
	$_SESSION['user_is_logged_in'] = 1;

	foreach($reg_DefaultPages as $page_name => $permission){
		$qry_insert_permission = "INSERT INTO " . REG_USERS_PAGES  . " (user_id, page_name, permission) 
		VALUES ($user_id, '$page_name', '$permission')";
		do_query($qry_insert_permission);
		$_SESSION[$page_name] = $permission;
		}
}
	



header ("Location: " .REG_PAGE_AFTERREG . "?message=$message" );

?>